/**
 * WebSocket连接管理类
 * 负责处理WebSocket连接的建立、消息发送接收和断线重连
 */
import store from '@/store'

class WebSocketService {
    constructor() {
        this.ws = null
        this.url = ''
        this.reconnectAttempts = 0
        this.maxReconnectAttempts = 5
        this.reconnectInterval = 3000 // 重连间隔时间（毫秒）
        this.heartbeatInterval = null
        this.heartbeatTimer = null
        this.messageCallbacks = []
        this.isConnected = false
        this.reconnecting = false
    }

    /**
     * 初始化WebSocket连接
     * @param {String} url WebSocket服务器地址
     */
    connect(url) {
        if (this.ws) {
            this.close()
        }

        this.url = url
        this.reconnectAttempts = 0
        this.createConnection()
    }

    /**
     * 创建WebSocket连接
     */
    createConnection() {
        try {
            this.ws = new WebSocket(this.url)

            this.ws.onopen = this.onOpen.bind(this)
            this.ws.onmessage = this.onMessage.bind(this)
            this.ws.onclose = this.onClose.bind(this)
            this.ws.onerror = this.onError.bind(this)
        } catch (error) {
            console.error('WebSocket连接创建失败:', error)
            this.reconnect()
        }
    }

    /**
     * WebSocket连接成功回调
     */
    onOpen() {
        console.log('WebSocket连接已建立')
        this.isConnected = true
        this.reconnectAttempts = 0
        this.reconnecting = false

        // 发送认证信息
        this.sendAuth()

        // 启动心跳检测
        this.startHeartbeat()
    }

    /**
     * 发送认证信息
     */
    sendAuth() {
        const token = store.getters.token
        if (token) {
            this.send({
                type: 'auth',
                token: token
            })
        }
    }

    /**
     * 启动心跳检测
     */
    startHeartbeat() {
        this.heartbeatTimer = setInterval(() => {
            if (this.isConnected) {
                this.send({ type: 'ping' })
            }
        }, 30000) // 每30秒发送一次心跳
    }

    /**
     * 停止心跳检测
     */
    stopHeartbeat() {
        if (this.heartbeatTimer) {
            clearInterval(this.heartbeatTimer)
            this.heartbeatTimer = null
        }
    }

    /**
     * 接收WebSocket消息回调
     * @param {MessageEvent} event 
     */
    onMessage(event) {
        try {
            const message = JSON.parse(event.data)

            // 处理心跳响应
            if (message.type === 'pong') {
                return
            }

            // 处理普通消息
            console.log('收到WebSocket消息:', message)

            // 触发消息回调
            this.messageCallbacks.forEach(callback => {
                callback(message)
            })

            // 更新消息状态
            this.updateMessageState(message)
        } catch (error) {
            console.error('WebSocket消息解析错误:', error)
        }
    }

    /**
     * 更新消息状态
     * @param {Object} message 
     */
    updateMessageState(message) {
        // 根据消息类型更新状态
        switch (message.type) {
            case 'chat':
                // 处理聊天消息
                store.commit('addChatMessage', message)
                break
            case 'notification':
                // 处理通知消息
                store.commit('addNotification', message)
                store.commit('incrementNotificationCount')
                break
            default:
                break
        }
    }

    /**
     * WebSocket连接关闭回调
     * @param {CloseEvent} event 
     */
    onClose(event) {
        console.log('WebSocket连接已关闭:', event)
        this.isConnected = false
        this.stopHeartbeat()

        if (!event.wasClean) {
            this.reconnect()
        }
    }

    /**
     * WebSocket连接错误回调
     * @param {Event} error 
     */
    onError(error) {
        console.error('WebSocket连接错误:', error)
        this.isConnected = false
    }

    /**
     * 重新连接WebSocket
     */
    reconnect() {
        if (this.reconnecting || this.reconnectAttempts >= this.maxReconnectAttempts) {
            return
        }

        this.reconnecting = true
        this.reconnectAttempts++

        console.log(`WebSocket尝试重新连接(${this.reconnectAttempts}/${this.maxReconnectAttempts})...`)

        setTimeout(() => {
            this.createConnection()
        }, this.reconnectInterval)
    }

    /**
     * 发送WebSocket消息
     * @param {Object} data 消息数据
     */
    send(data) {
        if (!this.isConnected) {
            console.warn('WebSocket未连接，无法发送消息')
            return false
        }

        try {
            this.ws.send(JSON.stringify(data))
            return true
        } catch (error) {
            console.error('WebSocket消息发送失败:', error)
            return false
        }
    }

    /**
     * 发送聊天消息
     * @param {String} to 接收者ID
     * @param {String} content 消息内容
     * @param {String} type 消息类型 (text, image, voice, video)
     * @param {Object} extra 额外信息
     */
    sendChatMessage(to, content, type = 'text', extra = {}) {
        return this.send({
            type: 'chat',
            to: to,
            content: content,
            messageType: type,
            timestamp: Date.now(),
            ...extra
        })
    }

    /**
     * 注册消息处理回调
     * @param {Function} callback 回调函数
     */
    onMessage(callback) {
        if (typeof callback === 'function' && !this.messageCallbacks.includes(callback)) {
            this.messageCallbacks.push(callback)
        }
    }

    /**
     * 移除消息处理回调
     * @param {Function} callback 回调函数
     */
    offMessage(callback) {
        const index = this.messageCallbacks.indexOf(callback)
        if (index !== -1) {
            this.messageCallbacks.splice(index, 1)
        }
    }

    /**
     * 关闭WebSocket连接
     */
    close() {
        if (this.ws) {
            this.stopHeartbeat()
            this.isConnected = false
            this.ws.close()
            this.ws = null
        }
    }
}

// 创建WebSocket服务单例
const webSocketService = new WebSocketService()

export default webSocketService